<script setup>
import { ref,onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryPageApi , addApi, queryInfoApi, updateApi, deleteApi, handleViolationApi} from '@/api/stu'
import { queryAllApi as queryAllClazzApi } from '@/api/clazz'
//钩子函数
onMounted(() => {
  // 获取学员列表数据
  queryPage()
  // 加载所有的班级数据下拉框
  queryAllClazz()   
})
// 搜索表单数据
let searchStu = ref({clazzId: '',degree: '',name: ''}) // 学员列表数据 姓名 学号 班级 性别 手机号 最高学历 违纪次数 违纪扣分 最后操作时间 操作(编辑 违纪 删除)
// 学员表格数据
const stuList = ref([])
// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
//最高学历下拉框数据
const degreeList = ref([{ name: '初中', value: 1 },{ name: '高中', value: 2 },{ name: '大专', value: 3 },{ name: '本科', value: 4 },{ name: '硕士', value: 5 },{ name: '博士', value: 6 }])

//所属班级下拉框数据
const clazzList = ref([])
//加载所有的班级数据
const queryAllClazz = async () => {
  let result = await queryAllClazzApi()
  if(result.code) {
    clazzList.value = result.data
  }
}
//每页展示条数改变
const handleSizeChange = (pageSize) => {
  pagination.value.pageSize = pageSize
  queryPage()
}
//当前页改变
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  queryPage()
}

// 分页查询学员列表数据
const queryPage =async () => {
  const result = await queryPageApi(
    searchStu.value.name,
    searchStu.value.degree,
    searchStu.value.clazzId,
    pagination.value.currentPage,
    pagination.value.pageSize
  )
  if(result.code) {
    stuList.value = result.data.rows
    pagination.value.total = result.data.total
  }
}
//清空搜索栏
const clear = () => {
  searchStu.value = {clazzId:'', degree:'', name:'',}
  queryPage()
}

//新增/修改学员
let dialogFormVisible = ref(false)
let labelWidth = ref(100)
let formTitle = ref('')
//性别下拉框数据
const genders = ref([{ name: '男', value: 1 },{ name: '女', value: 2 }])
//是否院校学员下拉框数据
const whethers = ref([{ name: '是', value: 1 },{ name: '否', value: 0 }])
//学生对象表单数据
let stu = ref({
  name: '',
  no: '',
  gender: '',
  phone: '',
  idCard: '',
  isCollege: '',
  address: '',
  degree: '',
  graduationDate: '',
  clazzId: ''
})
//表单校验规则
const stuFormRef = ref()
const rules = ref({
  name: [
    { required: true, message: '姓名为必填项', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度为2-20个字', trigger: 'blur' }
  ],
  no: [
    { required: true, message: '学号为必填项', trigger: 'blur' },
    { min: 10, max: 10, message: '学号长度为10个字', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '性别为必填项', trigger: 'change' }],
  phone: [
    { required: true, message: '手机号为必填项', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/g, message: '请输入合法的手机号', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '身份证号为必填项', trigger: 'blur' },
    { pattern: /^\d{18}$/g, message: '请输入合法的身份证号', trigger: 'blur' }
  ],
  isCollege: [
    { required: true, message: '是否院校学员为必填项', trigger: 'change' }
  ]
})
//清空表单
const clearStu = () => {
  stu.value = {
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: ''
  }
}
//记录员工复选框选中的id
const selectedStuIds = ref([]);
//复选框选中项发生变化
//map 方法会自动将数组中的每个元素作为参数传递给回调函数，并将回调函数的返回值组合成一个新数组返回。
const handleSelectionChange = (selection) =>{
  selectedStuIds.value = selection.map((item) => item.id)
}

//新增学员
const addStu = () => {
  formTitle.value = '新增学员'
  dialogFormVisible.value = true
  resetForm()
}
//编辑学员
const handleEdit = async (id) => {
  resetForm
  formTitle.value = '编辑学员'
  let result = await queryInfoApi(id)
  if(result.code) {
    stu.value = result.data
    dialogFormVisible.value = true
  }
}

//重置表单
const resetForm = () => {
  stuFormRef.value.resetFields()
}
//保存学员
const save = async () => {
  await stuFormRef.value.validate(async (valid) => {
    if(!valid) return
    let result = null
    if(stu.value.id) {//编辑
      result = await updateApi(stu.value)
    } else {//新增
      result = await addApi(stu.value)
    }
    if(result.code) {
      ElMessage.success('操作成功')
      dialogFormVisible.value = false
      resetForm()
      queryPage()
    }
  })
}
//删除学员
//根据ID删除单个学生
const handleDelete = async (id) => {
  ElMessageBox.confirm('此操作将永久删除该学员, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let result = await deleteApi(id)
    if(result.code) {
      ElMessage.success('删除成功')
      queryPage()
    }else {
      ElMessage.error(result.msg)
    }
  }).catch(() => {
    ElMessage.info('您已取消删除')
  })
}
//根据ID批量删除学生
const deleteByIds = async () => {
  if(selectedStuIds.value.length == 0) {
    ElMessage.warning('请选择要删除的学员')
    return
  }
  ElMessageBox.confirm('此操作将永久删除选中的学员, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let result = await deleteApi(selectedStuIds.value)
    if(result.code) {
      ElMessage.success('删除成功')
      queryPage()
    }else {
      ElMessage.error(result.msg)
    }
  }).catch(() => {
    ElMessage.info('您已取消删除')
  })
}

//违纪处理 confirm和prompt的区别在于confirm只有一个确定按钮，而prompt有确定和取消两个按钮
//inputPattern: /\d?/ 用于限制输入框只能输入数字 
const handleViolation = async (id) => {
  ElMessageBox.prompt('请输入违纪扣分', '提示',  {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\d?/,
    inputErrorMescahsnsage: '数据无效',
  }).then(async (val) => {
    console.log('val: ' + val);
    let result = await handleViolationApi(id,val.value)
    if(result.code) {
      ElMessage.success('处理成功')
      queryPage()
    }else {
      ElMessage.error(result.msg)
    }
  }).catch((val) => {
    console.log('val: ' + val);
    ElMessage.info('您已取消违纪')
  })
}


</script>

<template>
  <h1>学员管理</h1>
  
  <!-- 条件搜索表单 -->
   <!-- 搜索条件 姓名 最高学历 所属班级 查询清空按钮 -->
      <!-- el-form-item 组件的 prop 属性主要用于表单验证。如果你不需要对表单项进行验证，那么可以省略 prop 属性。 -->
  <div class="contaner">
    <el-form :inline="true" :model="searchStu" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="searchStu.name" placeholder="请输入学生姓名"/>
      </el-form-item>

      <el-form-item label="最高学历">
        <el-select v-model="searchStu.degree" placeholder="请选择">
          <el-option v-for="degree in degreeList" :key="degree.value" :label="degree.name" :value="degree.value" />
         
        </el-select>
      </el-form-item>

      <el-form-item label="所属班级">
        <el-select v-model="searchStu.clazzId" placeholder="请选择">
          <el-option v-for="clazz in clazzList" :key="clazz.id" :label="clazz.name" :value="clazz.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="queryPage()">查询</el-button>
        <el-button type="info" @click="clear()">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

   <!-- 功能按钮 添加学员 批量删除 -->
  <el-button  type="primary" @click="addStu">+新增学员</el-button>
  <el-button type="danger" @click="deleteByIds">批量删除</el-button>

  <!-- 表格 -->
   <!-- @selection-change="handleSelectionChange" 用于监听复选框选中项的变化 -->
   <!--表格列数据为复选框 姓名 学号 班级 性别 手机号 最高学历 违纪次数 违纪扣分 最后操作时间 操作(编辑 违纪按钮 删除) -->
  <el-table :data="stuList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="35"></el-table-column>
    <el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column>
    <el-table-column prop="no" label="学号" width="130" align="center"></el-table-column>
    <el-table-column prop="clazzName" label="班级" width="160" align="center"></el-table-column>
    <el-table-column prop="gender" label="性别" width="70" align="center">
      <template #default="scope">
        {{scope.row.gender == 1 ? '男' : '女'}}
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号" width="130" align="center"></el-table-column>
    <el-table-column prop="degree" label="最高学历" width="90" align="center">
      <template #default="scope">
        <span v-if="scope.row.degree == 1">初中</span>
          <span v-else-if="scope.row.degree == 2">高中</span>
          <span v-else-if="scope.row.degree == 3">大专</span>
          <span v-else-if="scope.row.degree == 4">本科</span>
          <span v-else-if="scope.row.degree == 5">硕士</span>
          <span v-else-if="scope.row.degree == 6">博士</span>
          <span v-else>其他</span>
      </template>
    </el-table-column>
    <el-table-column prop="violationCount" label="违纪次数" width="85" align="center"></el-table-column>
    <el-table-column prop="violationScore" label="违纪扣分" width="85" align="center"></el-table-column>
    <el-table-column prop="updateTime" label="最后操作时间" width="170" align="center"></el-table-column>
    <el-table-column fixed="right" label="操作" align="center">
      <template #default="scope">
        <el-button size="small"  type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
        <el-button size="small"  type="warning" @click="handleViolation(scope.row.id)">违纪</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

<!-- 新增/修改学员对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="formTitle" width="50%" >
    <el-form :model="stu" ref="stuFormRef" :rules="rules">
       <!-- 第一行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" :label-width="labelWidth" prop="name">
            <el-input v-model="stu.name" placeholder="请输入学员姓名"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" :label-width="labelWidth" prop="no">
            <el-input v-model="stu.no" placeholder="请输入学员学号"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" :label-width="labelWidth"  prop="gender">
            <el-select v-model="stu.gender" placeholder="请选择" style="width: 100%;">
              <el-option v-for="gender in genders" :label="gender.name" :value="gender.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" :label-width="labelWidth"  prop="phone">
            <el-input v-model="stu.phone" placeholder="请输入手机号"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="身份证号" :label-width="labelWidth"  prop="idCard">
            <el-input v-model="stu.idCard" placeholder="请输入身份证号"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校" :label-width="labelWidth" prop="isCollege">
            <el-select v-model="stu.isCollege" placeholder="请选择" style="width: 100%;">
              <el-option v-for="w in whethers" :label="w.name" :value="w.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系地址" :label-width="labelWidth">
            <el-input v-model="stu.address" placeholder="请输入联系地址"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历" :label-width="labelWidth">
            <el-select v-model="stu.degree" placeholder="请选择" style="width: 100%;">
              <el-option v-for="degree in degreeList" :label="degree.name" :value="degree.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- 第五行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="毕业时间" :label-width="labelWidth">
            <el-date-picker v-model="stu.graduationDate" type="date" placeholder="请选择毕业时间" value-format="YYYY-MM-DD" style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级" :label-width="labelWidth">
            <el-select v-model="stu.clazzId" placeholder="请选择" style="width: 100%;">
              <el-option v-for="clazz in clazzList" :label="clazz.name" :value="clazz.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!--底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false; resetForm(stuFormRef)">取消</el-button>
        <el-button type="primary" @click="save()">保存</el-button>
      </span>
    </template>
      

  </el-dialog>

</template>

<style scoped>
.contaner {
  margin: 20px;
}

</style>